
#include <vector>
#include <algorithm>
#include <queue>
#include <iostream>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include "EfficientMap.cc"
#include "TwoWayList.cc"
#include "Types.cc"
#include "BlockSortedTempTable.h"

class InRecord
{

private:

#include "Atts.cc"

    // Example of what would be in Atts.cc
    /*
      Int n_n_nationkey;
      Str n_n_name;
      Int n_n_regionkey;
      Str n_n_comment;
    */


public:

    InRecord  () {}
    ~InRecord  () {}

    bool ReadIn (FILE *fromMe)
	{
	    bool res;

#include "ReadIn.cc"

	    // Example of what would be in ReadIn.cc
	    /*
	      res = n_n_nationkey.ReadIn(fromMe);
	      res = n_n_name.ReadIn(fromMe);
	      res = n_n_regionkey.ReadIn(fromMe);
	      res = n_n_comment.ReadIn(fromMe);
	    */

	    fgetc_unlocked(fromMe);

	    return res;
	}

    void WriteBuffer(FILE *toMe)
	{

#include "WriteBuffer.cc"

	    // Example of what would be in WriteBuffer.cc
	    /*
	      n_n_nationkey.WriteOut(toMe);
	      n_n_name.WriteOut(toMe);
	      n_n_regionkey.WriteOut(toMe);
	      n_n_comment.WriteOut(toMe);
	    */

	  fputc_unlocked('\n', toMe);
	}

    void WriteOut (FILE *toMe)
	{

#include "WriteOut.cc"

	    // Example of what would be in WriteOut.cc
	    /*
	      Int att1 = n_n_nationkey;
	      Str att2 = n_n_name;
	      Int att3 = n_n_regionkey;
	      Str att4 = n_n_comment;
	      att1.WriteOut(toMe);
	      att2.WriteOut(toMe);
	      att3.WriteOut(toMe);
	      att4.WriteOut(toMe);
	    */

	  fputc_unlocked ('\n', toMe);
	}

#include "SortFunctions.cc"

    // Example of what would be included in SortFunctions.cc
    /*
      Int sortFunction1() const { return n_n_nationkey; }
      Str sortFunction2() const { return n_n_name; }
      Int sortFunction3() const { return n_n_regionkey; }
    */

    bool operator < (const InRecord & r2) const
	{

#include "Compare.cc"

	    // example of what would be in Compare.cc
	    /*
	      if (sortFunction1() > r2.sortFunction1()) return true;
	      if (sortFunction1() < r2.sortFunction1()) return false;
	      if (sortFunction2() < r2.sortFunction2()) return true;
	      if (sortFunction2() > r2.sortFunction2()) return false;
	      if (sortFunction3() < r2.sortFunction3()) return true;
	      if (sortFunction3() > r2.sortFunction3()) return false;
	    */

	    return false;
	}
};

int
main(int argc, char **argv)
{
    if (argc != 3)
    {
	fprintf(stderr, "Usage: TPOrderBy inputFile outputFile");
	exit(-1);
    }

    char *inputFile = argv[1];
    char *outputFile = argv[2];

    BlockSortedTempTable<InRecord> *bstt = new BlockSortedTempTable<InRecord>(inputFile);
    bstt->writeBlocks();
    bstt->initForRead();

    FILE *f = fopen(outputFile, "w");

    InRecord r;
    while (bstt->next(r))
    {
	r.WriteOut(f);
    }

    bstt->cleanup();

    fclose(f);

    return 0;
}

